package com.szt.sy.controller.system.dicttype;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.szt.sy.anontation.Authority;
import com.szt.sy.anontation.AuthorityConfig;
import com.szt.sy.anontation.SysLog;
import com.szt.sy.common.AuthorityCommon;
import com.szt.sy.controller.base.AdminBaseController;
import com.szt.sy.entity.common.TreeNode;
import com.szt.sy.entity.system.DictType;
import com.szt.sy.service.system.dicttype.DictTypeService;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.excel.ObjectExcelView;
import com.szt.sy.util.json.JsonUtils;
import com.szt.sy.vo.rep.base.RepBaseVO;

/**
 * @author wwy
 *
 *         <p>
 *         说明：数据字典类型控制器<br/>
 *         创建时间：2018-01-15
 *         </p>
 */
@Controller
@AuthorityConfig(prefix = "/admin/dicttype/tree")
@RequestMapping(value = "admin/dicttype")
public class DictTypeController extends AdminBaseController {
	
	@Autowired
	private DictTypeService dicttypeService;
	
	/***
	 * 去树形页面
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "tree")
	public ModelAndView treePage() {
		ModelAndView mv = new ModelAndView();
		List<DictType> dictTypes = dicttypeService.treeList(DictType.ROOT_ID);
		List<TreeNode> treeNodes = new ArrayList<>();
		if (dictTypes != null) {
			for (DictType item : dictTypes) {
				TreeNode treeNode = new TreeNode();
				treeNode.setChecked(true);
				treeNode.setId(item.getId());
				treeNode.setName(item.getName());
				treeNode.setPid(item.getPid());
				treeNode.setTarget("treeFrame");
				treeNode.setUrl("/admin/dicttype/list?pid=" + item.getId());
				List<TreeNode> nodes = new ArrayList<>();
				if (item.getNodes() != null) {
					for (DictType node : item.getNodes()) {
						TreeNode treeNode2 = new TreeNode();
						treeNode2.setChecked(true);
						treeNode2.setId(node.getId());
						treeNode2.setName(node.getName());
						treeNode2.setPid(node.getPid());
						// treeNode2.setTarget("treeFrame");
						// treeNode2.setUrl("/admin/goodstype/goPage?parentId="
						// + node.getId());
						nodes.add(treeNode2);
					}
				}
				treeNode.setNodes(nodes);
				treeNodes.add(treeNode);
			}
			
		}
		mv.addObject("zTreeNodes", JsonUtils.beanToString(treeNodes));
		mv.setViewName("system/dicttype/dicttype_ztree");
		return mv;
	}
	
	/**
	 * 去列表页面
	 * 
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "/list")
	public ModelAndView goPage(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/dicttype/dicttype_list");
		mv.addObject("queryParam", map);
		// 按钮权限
		
		return mv;
	}
	
	/**
	 * 列表数据
	 */
	@SysLog("查询数据字典类型列表数据")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/list")
	@ResponseBody
	public RepBaseVO list(Page<DictType> page, @RequestParam Map<String, Object> map) {
		RepBaseVO repVO = new RepBaseVO<>();
		processParams(map);
		page = dicttypeService.list(new Page<DictType>(page.getCurrent(), page.getSize()), map);
		List<DictType> varList = page.getRecords();
		Map<String, Object> resultInfo = new HashMap<>(2);
		resultInfo.put("data", varList);
		resultInfo.put("total", page.getTotal());
		return repVO.setCommonSuccess().setData(resultInfo);
	}
	
	/**
	 * 去新增页面
	 */
	@Authority(name = AuthorityCommon.ADD)
	@GetMapping(value = "/add")
	public ModelAndView goAdd(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/dicttype/dicttype_edit");
		DictType entity = new DictType();
		entity.setPid(Long.parseLong(map.get("pid").toString()));
		mv.addObject("msg", "add");
		mv.addObject("entity", entity);
		mv.addObject("pd", map);
		return mv;
	}
	
	/**
	 * 保存
	 */
	@SysLog("添加数据字典类型数据")
	@Authority(name = AuthorityCommon.ADD)
	@PostMapping(value = "/add")
	@ResponseBody
	public RepBaseVO save(DictType entity) {
		RepBaseVO repVO = new RepBaseVO();
		entity.setType(entity.getType().toUpperCase().trim());
		entity.setEditable(DictType.EDITABLE_FALSE);
		entity.setVersion(1L);
		entity.setAddDate(new Date());
		// 判断类型是否存在
		boolean typeExist = dicttypeService
				.selectCount(new EntityWrapper<DictType>().eq("type", entity.getType())) >= 1;
		if (typeExist) {
			return repVO.setCommonFail().setMes("类型已存在");
		}
		dicttypeService.insert(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 去修改页面
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@GetMapping(value = "/edit")
	public ModelAndView goEdit(Long id) {
		ModelAndView mv = this.getModelAndView();
		DictType entity = dicttypeService.selectById(id);
		mv.setViewName("system/dicttype/dicttype_edit");
		mv.addObject("msg", "edit");
		mv.addObject("entity", entity);
		return mv;
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改数据字典类型数据")
	@Authority(name = AuthorityCommon.EDIT)
	@PostMapping(value = "/edit")
	@ResponseBody
	public RepBaseVO edit(DictType entity) {
		RepBaseVO repVO = new RepBaseVO<>();
		entity.setType(entity.getType().toUpperCase().trim());
		// 判断类型是否存在
		boolean typeExist = dicttypeService
				.selectCount(new EntityWrapper<DictType>().eq("type", entity.getType()).ne("id", entity.getId())) >= 1;
		if (typeExist) {
			return repVO.setCommonFail().setMes("类型已存在");
		}
		dicttypeService.updateById(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除数据字典类型数据")
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/delete")
	@ResponseBody
	public RepBaseVO delete(Long id) {
		dicttypeService.deleteById(id);
		return RepBaseVO.newIntance().setCommonSuccess();
	}
	
	/**
	 * 批量删除
	 */
	@SysLog("批量删除数据字典类型数据")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/deleteAll")
	@ResponseBody
	public RepBaseVO deleteAll(String ids) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (null != ids && !"".equals(ids)) {
			String[] idArray = ids.split(",");
			dicttypeService.deleteBatchIds(Lists.newArrayList(idArray));
			
		}
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 导出到excel
	 */
	@SysLog("导出数据字典类型excel")
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/excel")
	public ModelAndView exportExcel(@RequestParam Map<String, Object> map) {
		ModelAndView mv = new ModelAndView();
		processParams(map);
		Map<String, Object> dataMap = new HashMap<String, Object>(2);
		List<String> titles = new ArrayList<String>();
		titles.add("名称");
		titles.add("类型");
		titles.add("能否修改");
		titles.add("父级id，没有父级则为-1");
		titles.add("排序");
		dataMap.put("titles", titles);
		List<DictType> varOList = dicttypeService.listAll(map);
		List<Map<String, Object>> varList = new ArrayList<Map<String, Object>>();
		for (DictType entity : varOList) {
			Map<String, Object> vpd = new HashMap<String, Object>(30);
			vpd.put("var1", entity.getName());
			vpd.put("var2", entity.getType());
			vpd.put("var3", entity.getEditable());
			vpd.put("var4", entity.getPid());
			vpd.put("var5", entity.getSort());
			varList.add(vpd);
		}
		
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}
	
	/***
	 * 处理输入参数
	 * 
	 * @param map
	 */
	private void processParams(Map<String, Object> map) {
		String sStartDate = (String) map.get("lastStart");
		String sEndDate = (String) map.get("lastEnd");
		if (StringUtils.isBlank(sStartDate)) {
			map.put("lastStart", null);
		} else {
			map.put("lastStart", DateUtil.getStartTimeOfDate(sStartDate));
		}
		if (StringUtils.isBlank(sEndDate)) {
			map.put("lastEnd", null);
		} else {
			map.put("lastEnd", DateUtil.getEndTimeOfDate(sEndDate));
		}
	}
	
}
